package com.gc.flashview;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.view.ViewPager.PageTransformer;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.gc.flashview.effect.AccordionTransformer;
import com.gc.flashview.effect.CubeTransformer;
import com.gc.flashview.effect.DefaultTransformer;
import com.gc.flashview.effect.DepthPageTransformer;
import com.gc.flashview.effect.InRightDownTransformer;
import com.gc.flashview.effect.InRightUpTransformer;
import com.gc.flashview.effect.RotateTransformer;
import com.gc.flashview.effect.ZoomOutPageTransformer;
import com.gc.flashview.listener.OnItemClickListener;
import com.gc.flashview.utils.FileUtil;
import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.tentinet.flashviewproject.R;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义控件 实现图片轮回
 */
public class FlashView extends FrameLayout {
    private DisplayImageOptions options;
    private ImageHandler mhandler = new ImageHandler(new WeakReference<FlashView>(this));
    /** 图片地址集合*/
    private List<String> imageUris;
    private Context context;
    /** 图片集合用于暂时存储*/
    private List<ImageView> imageViewsList;
    /** 点集合用于暂时存储*/
    private List<ImageView> dotViewsList;
    /** 点容器*/
    private LinearLayout mLinearLayout;
    /** 图片容器*/
    private ViewPager mViewPager;
    /** 向外提供接口 对item 实施监听*/
    private OnItemClickListener mFlashViewListener;//向外提供接口
    private boolean isTwo = false;
    private int pos;
    /** 图片切换的动画效果*/
    private int effect;//
    /** 是不需要滚动*//*
    private boolean isNeededAutoRoll = true;*/
    public FlashView(Context context) {
        this(context, null);
    }

    public FlashView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlashView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        //读取该自定义控件自定义的属性
        this.context = context;
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.FlashView);
        effect = mTypedArray.getInt(R.styleable.FlashView_effect, 2);
        initUI(context);
        if (!(imageUris.size() <= 0)) {
            setImageUris(imageUris);//
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        //adjustScreen(this,0.0f);
        super.onLayout(changed, left, top, right, bottom);
    }

    /**
     * 初始化ImageLoader显示配置类
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,16:06
     * <h3>UpdateTime</h3> 2016/1/7,16:06
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     */
    private void initBitmapDisplayOption() {
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageOnLoading(R.mipmap.ic_defaule_fail_bg)
                .showImageForEmptyUri(R.mipmap.ic_defaule_fail_bg)
                .showImageOnFail(R.mipmap.ic_defaule_fail_bg)
                .build();

    }

    /**
     * 在下载图片之前如果imageLoader未初始化，必须调用该方法对imageLoader进行初始化
     * （一般情况：使用 imageLoader加载图片 都已经在全局类中初始化过了，无需再调用此方法）。
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,16:28
     * <h3>UpdateTime</h3> 2016/1/7,16:28
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * 
     * @param context 上下文
     */
    public void initImageLoadConfig( Context context) {
        ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(context);
        DiskCache cache = new UnlimitedDiscCache(FileUtil.getImageCache(context));
        //配置文件保存的路径
        builder.diskCache(cache);
        //设置保存图片的最大张数
        builder.diskCacheFileCount(500);
        //配置磁盘缓存保存图片的最大内存
        builder.diskCacheSize(50 * 1024 * 1024);
        // 获取系统分配给应用程序的最大内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int maxSize = maxMemory / 8;
        //配置内存缓存的大小
        builder.memoryCacheSize(maxSize);
        //配置保存图片的命名器
        builder.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        ImageLoader.getInstance().init(builder.build());
    }

    /**
     * 设置是否自动滚动
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,18:41
     * <h3>UpdateTime</h3> 2016/1/7,18:41
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     */
    /*public void setAutoScroll( boolean isAutoRoll){
        this.isNeededAutoRoll = isAutoRoll;
    }*/

    /**
     *
     * 设置监听
     *
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,16:34
     * <h3>UpdateTime</h3> 2016/1/7,16:34
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param mFlashViewListener
     */
    public void setOnPageClickListener(OnItemClickListener mFlashViewListener) {
        this.mFlashViewListener = mFlashViewListener;
    }
    private void initUI(Context context) {
        initBitmapDisplayOption();

        imageViewsList = new ArrayList<ImageView>();
        dotViewsList = new ArrayList<ImageView>();
        imageUris = new ArrayList<String>();
        LayoutInflater.from(context).inflate(R.layout.flash_view_layout, this, true);
        mLinearLayout = (LinearLayout) findViewById(R.id.flash_lLayout);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        // 1.设置幕后item的缓存数目
//        mViewPager.setOffscreenPageLimit(2);
        // 2.设置页与页之间的间距
//        mViewPager.setPageMargin( -300);
    }

    /**
     * 图片适配屏幕
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,17:14
     * <h3>UpdateTime</h3> 2016/1/7,17:14
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param imageViewShower FlashView 对象
     * @param f 高度占有高度的比例 默认 0.55
     */

    public void adjustScreen(FlashView imageViewShower,float f) {
        /*获取手机屏幕分辨率信息的类*/
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        /*手机屏幕的宽度*/
        int widthScreen = displayMetrics.widthPixels;
        /*手机屏幕的高度*/
        int heightScreen = displayMetrics.heightPixels;
        /*获取图片的参数*/
        ViewGroup.LayoutParams layoutParamsImView = imageViewShower.getLayoutParams();

        /*设置图片的宽度*/
        layoutParamsImView.width = (widthScreen);
        /*设置图片的高度*/
        if (f != 0.0f){
            layoutParamsImView.height = (int)(widthScreen * f) ;
        }else {
            layoutParamsImView.height = (int)(widthScreen * 0.55f) ;
        }
        imageViewShower.setLayoutParams(layoutParamsImView);
    }


    /**
     * 设置图片加载的地址
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,17:40
     * <h3>UpdateTime</h3> 2016/1/7,17:40
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param imageuris 图片地址集合
     */
    public void setImageUris(List<String> imageuris) {

        if (imageUris.size() > 0) {
            imageUris.clear();
            imageViewsList.clear();
            dotViewsList.clear();
            mLinearLayout.removeAllViews();
        }


        if (imageuris.size() <= 0)// 如果得到的图片张数为0，则增加一张默认的图片
        {
            imageUris.add("drawable://" + R.mipmap.icon_null_bg);
        } else {

            if (imageuris.size() == 2) {
                isTwo = true;
                imageUris.addAll(imageuris);
                imageUris.addAll(imageuris);
            } else {
                isTwo = false;
                imageUris.addAll(imageuris);
            }
            //
//		 for (int i = 0; i < imageuris.size(); i++)
//		 {
            //
//		 imageUris.add(imageuris.get(i));
//		 if(i==1)
//		 {
//		 imageUris.add(imageuris.get(0));
//		 }
//		 }
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(5, 0, 0, 0);

        for (int i = 0; i < imageUris.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ScaleType.FIT_XY);// X和Y方向都填满


            ImageLoader.getInstance().displayImage(imageUris.get(i), imageView, options);
            imageViewsList.add(imageView);


            ImageView viewDot = new ImageView(getContext());
            if (i == 0) {
                viewDot.setBackgroundResource(R.mipmap.dot_white);
            } else {
                viewDot.setBackgroundResource(R.mipmap.dot_light);
            }
            viewDot.setLayoutParams(lp);


            if (isTwo)//为两张图片时加入的判断
            {
                if (i > 1) {

                } else {
                    dotViewsList.add(viewDot);
                    mLinearLayout.addView(viewDot);
                }
            } else {
                dotViewsList.add(viewDot);
                mLinearLayout.addView(viewDot);
            }

        }


        mViewPager.setFocusable(true);
        mViewPager.setAdapter(new MyPagerAdapter());
        mViewPager.setOnPageChangeListener(new MyPageChangeListener());
        setEffect(effect);


        /**
         * 轮回逻辑
         */
        if (imageUris.size() <= 1)//图片小于等于1张时，不轮播
        {

        } else {

            // 利用反射修改自动轮播的动画持续时间
            try {
                Field field = ViewPager.class.getDeclaredField("mScroller");
                field.setAccessible(true);
                FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(), new AccelerateInterpolator());
                field.set(mViewPager, scroller);
                scroller.setmDuration(1000);
                mViewPager.setCurrentItem(100 * imageViewsList.size());
                mhandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);

            } catch (Exception e) {
               e.printStackTrace();
            }
        }

    }

    /**
     * 切换轮播小点的显示
     *
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,16:34
     * <h3>UpdateTime</h3> 2016/1/7,16:34
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param selectItems
     */
    private void setImageBackground(int selectItems) {
        for (int i = 0; i < dotViewsList.size(); i++) {
            if (i == selectItems % dotViewsList.size()) {
                dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_white);
            } else {
                dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_light);
            }
        }
    }

    /**
     * 数据适配器
     *
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,16:34
     * <h3>UpdateTime</h3> 2016/1/7,16:34
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     */
    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            position = position % imageViewsList.size();


            if (position < 0) {
                position = position + imageViewsList.size();

            }
            if (isTwo) {
                pos = position % 2;
            } else {
                pos = position;
            }
            final int posclick = pos;
            View view = imageViewsList.get(position);
            view.setTag(position);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mFlashViewListener != null) {
                        mFlashViewListener.onItemClick(posclick);
                    } else {

                    }

                }
            });
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewPager pager = (ViewPager) vp;
                pager.removeView(view);
            }
            ((ViewPager) container).addView(view);
            return view;
        }

        @Override
        public int getCount() {
            if (imageUris.size() <= 1) {
                return 1;
            } else {
                return Integer.MAX_VALUE;
            }

        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }



    private class MyPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case ViewPager.SCROLL_STATE_DRAGGING://滚动状态
                    mhandler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                    break;
                case ViewPager.SCROLL_STATE_IDLE://空闲状态
                    mhandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                    break;
                default:
                    break;
            }

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
//		 System.out.println("GGGGGGGGG");
//		 mhandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE,ImageHandler.MSG_DELAY);
        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
            mhandler.sendMessage(Message.obtain(mhandler, ImageHandler.MSG_PAGE_CHANGED, pos, 0));
            setImageBackground(pos);

        }

    }

    @SuppressWarnings("unused")
    private void destoryBitmaps() {
        for (int i = 0; i < imageViewsList.size(); i++) {
            ImageView imageView = imageViewsList.get(i);
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                drawable.setCallback(null);
            }
        }
    }

    /**
     * 设置动画效果
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,18:04
     * <h3>UpdateTime</h3> 2016/1/7,18:04
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param selectEffect
     */
    public void setEffect(int selectEffect) {
        switch (selectEffect) {
            case 0://左右折叠效果
                setPageTransformer(true, new AccordionTransformer());
                break;
            case 1://立方体效果
                setPageTransformer(true, new CubeTransformer());
                break;
            case 2://默认效果
                setPageTransformer(true, new DefaultTransformer());
                break;
            case 3://深入浅出效果
                setPageTransformer(true, new DepthPageTransformer());
                break;
            case 4://右下角进入效果
                setPageTransformer(true, new InRightDownTransformer());
                break;
            case 5://右上角进入效果
                setPageTransformer(true, new InRightUpTransformer());
                break;
            case 6://旋转效果
                setPageTransformer(true, new RotateTransformer());
                break;
            case 7://淡入淡出效果
                setPageTransformer(true, new ZoomOutPageTransformer());
                break;
            default:
                break;
        }
    }

    /**
     * 设置切换效果
     *
     * @param b
     * @param rotateTransformer
     */
    public void setPageTransformer(boolean b, PageTransformer rotateTransformer) {
        // TODO Auto-generated method stub
        mViewPager.setPageTransformer(b, rotateTransformer);
    }

    /**
     * FixedSpeedScroller类的源码来源于网络，在此谢过贡献此代码的道友
     */
    public class FixedSpeedScroller extends Scroller {
        private int mDuration = 1500;

        public FixedSpeedScroller(Context context) {
            super(context);
        }

        public FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {

            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {

            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        public void setmDuration(int time) {
            mDuration = time;
        }

        public int getmDuration() {
            return mDuration;
        }
    }

    private static class ImageHandler extends Handler {
        /** 更新*/
        protected static final int MSG_UPDATE_IMAGE = 1;
        /** 保持*/
        protected static final int MSG_KEEP_SILENT = 2;

        protected static final int MSG_BREAK_SILENT = 3;

        protected static final int MSG_PAGE_CHANGED = 4;
        /** 延迟时间*/
        protected static final long MSG_DELAY = 2000;

        private WeakReference<FlashView> weakReference;
        private int currentItem = 0;

        protected ImageHandler(WeakReference<FlashView> wk) {
            weakReference = wk;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            FlashView activity = weakReference.get();
            if (activity == null) {
                return;
            }
            if (activity.mhandler.hasMessages(MSG_UPDATE_IMAGE)) {
                if (currentItem > 0)// 这里必须加入currentItem>0的判断，否则不能完美的自动轮播
                {
                    activity.mhandler.removeMessages(MSG_UPDATE_IMAGE);
                }
            }
            switch (msg.what) {
                case MSG_UPDATE_IMAGE:
                    currentItem++;
                    activity.mViewPager.setCurrentItem(currentItem);
                    activity.mhandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_KEEP_SILENT:
                    break;
                case MSG_BREAK_SILENT:
                    activity.mhandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_PAGE_CHANGED:
                    currentItem = msg.arg1;
                    activity.mhandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                default:
                    break;
            }
        }
    }
}

